package com.qf.web.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.SyncReadListener;
import com.qf.entity.OrderSetting;
import com.qf.entity.Result;
import com.qf.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/orderSetting")
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    //根据日期设置对应的预约设置数据
    @RequestMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingService.editNumberByOrderDate(orderSetting);
            return Result.success("预约设置成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("预约设置失败");
        }
    }

    //根据月份查询当前月份的预约设置
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String month){
      try {
          List<Map> list = orderSettingService.getOrderSettingByMonth(month);
          return Result.success(list);
      }catch (Exception e){
          e.printStackTrace();
          return Result.error("预约查询失败");
      }

    }

    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile, HttpServletRequest req) throws IOException {
        //解决文件重名
        if (excelFile != null){
            //获取原始文件名
            String originalFilename = excelFile.getOriginalFilename();
            System.out.println(originalFilename);
            //截取原文件名的后缀
            int idx = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(idx);

            String fileName = UUID.randomUUID().toString().replaceAll("-","") + suffix;

            //获取保存文件目录的真实位置
            String realPath = req.getServletContext().getRealPath("/uploadfiles");

            //创建最终保存文件的File对象
            File destFile = new File(realPath,fileName);

            excelFile.transferTo(destFile);

            //读取文件中的数据， 填充到数据库 (POI-原生操作非常复杂，面向过程的)
            //EasyExcel：阿里基于POI做了封装，面向对象，更加易用
            /*
                java.io.File file:  指定要读取的文件对象（还可以指定一个文件所在路径或者一个文件对应的输入流）
                Class head : 指定要读取的文件中每一行数据封装到哪个类型的对象中
                com.alibaba.excel.read.listener.ReadListener readListener》：读取文件过程中的回调对象
                    当EasyExcel在读取数据过程中，每读取到一行，会将数据封装到head类型的对象中，并通过这个回调对象的invoke回调给我们
             */
            List<OrderSetting> orderSettings = new ArrayList<>();
            EasyExcel.read(destFile,OrderSetting.class,new SyncReadListener(){
                @Override
                public void invoke(Object object, AnalysisContext context) {
                    //Object object就是封装到的每一个行数据的head类型的对象
                    orderSettings.add((OrderSetting) object);
                }
            }).doReadAll();

            //打印测试
            for (OrderSetting orderSetting : orderSettings) {
                System.out.println(orderSetting);
            }

            //将读取到的数据同步到数据库
            for (OrderSetting orderSetting : orderSettings) {
                orderSettingService.editNumberByOrderDate(orderSetting);
            }

            //成功
            return Result.success(null);
        }

        return Result.error("上传失败!");
    }
}
